package de.IIIfeed.MoneyPlanner;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;

import net.technologichron.manacalc.FloatPicker;

import org.kroz.activerecord.ActiveRecordException;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioGroup;

public class AddAndUpdate extends Activity {
    //private DatabaseHelper dbHelper;
    Item item;
    EditText title;
    FloatPicker amount;
    DatePicker start;
    RadioGroup type;
    
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.additem);
        
        //dbHelper = DatabaseHelper.getInstance(this);
        String caller = getIntent().getStringExtra("caller");
        if(caller.equals(".ShowItems")){
        	item = Manage.item;
        } else if(caller.equals(".MoneyPlanner")){
        	item = MoneyPlanner.item;
        }
        
        title = (EditText) findViewById(R.id.title);
        title.setText(item.title);
        
        amount = (FloatPicker) findViewById(R.id.amount);
        amount.setValue(item.amount);
        
        start = (DatePicker) findViewById(R.id.date);
        Calendar c = Calendar.getInstance();
        Log.i("load date",item.dateStart.toGMTString());
        c.setTimeInMillis(item.dateStart.getTime());
        start.updateDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
        
        type = (RadioGroup) findViewById(R.id.time);
        if(item.type == MoneyPlanner.ONCE){
        	type.check(R.id.onceRadio);
        } else {
        	type.check(R.id.periodicallyRadio);
        }
        
        findViewById(R.id.addButton).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String title = ((EditText) findViewById(R.id.title)).getText().toString();
				float amountFl = AddAndUpdate.this.amount.getValue();
				int type;
				if(((RadioGroup) findViewById(R.id.time)).getCheckedRadioButtonId() == R.id.onceRadio){
					type = MoneyPlanner.ONCE;
        		} else {
        			type = MoneyPlanner.PERIODICALLY;
        		}
				DatePicker dp = (DatePicker) findViewById(R.id.date);
				Date date = new Date(dp.getYear(),dp.getMonth(),dp.getDayOfMonth());
				Log.i("save date",date.toGMTString());
				item.amount = amountFl;
				item.dateStart = new Timestamp(date.getTime());
				item.title = title;
				item.type = type;
				try {
					item.save();
				} catch (ActiveRecordException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				finish();
			}
		});
    }
    

}